#include "atclient.h"

#include <QTextStream>

AtClient::AtClient(const char *com, int updateInterval, QObject *parent) : QObject(parent)
{
    serial = new Serial(this);
    auto dev = QString(com).toUpper();
    if(serial->open(dev, QSerialPort::Baud9600))
    {
        serial->setFrameGap(100);
        connect(serial, SIGNAL(frameIn(const QByteArray &)), this, SLOT(onFrameIn(const QByteArray &)));
    }
    else
    {
        exit(-1);
    }

    updateTimer = new QTimer(this);
    connect(updateTimer, SIGNAL(timeout()), this, SLOT(onUpdate()));
    updateTimer->start(updateInterval * 1000);
}

void AtClient::onFrameIn(const QByteArray &data)
{
    qDebug() << "RX:" << data;

    if(data.indexOf("+MIPLWRITE:") >= 0)
    {
        auto dls = data.split(',');
        QByteArray cmd = "AT+MIPLWRITERSP=0," + dls[1] + ",2\r\n";
        serial->send(cmd);
        qDebug() << "TX:" << cmd;
    }
}

void AtClient::onUpdate()
{
    QByteArray cmd = "AT+MIPLUPDATE=0,30000,0\r\n";
    serial->send(cmd);
    qDebug() << "TX:" << cmd;
}
